package com.example.su_shi_tan_sig_in.child

import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.util.Log
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.example.library_common.utils.normalShortToast
import com.example.su_shi_tan_bas_lib.base.BaseDataBindingFragment
import com.example.su_shi_tan_bas_lib.constant.CLICK_BLE
import com.example.su_shi_tan_bas_lib.networking.RestClient
import com.example.su_shi_tan_bas_lib.utils.OnTextListener
import com.example.su_shi_tan_core.db.LogInTokenManager
import com.example.su_shi_tan_sig_in.R
import com.example.su_shi_tan_sig_in.databinding.LoginAccountFragmentBinding

class LoginAccountFragment(loginProxy: LoginProxy) :
    BaseDataBindingFragment<LoginAccountFragmentBinding>(), LoginProxy by loginProxy,
    View.OnClickListener, OnTextListener {

    companion object {
        fun newInstance(loginProxy: LoginProxy): LoginAccountFragment {
            val args = Bundle()
            val fragment = LoginAccountFragment(loginProxy)
            fragment.arguments = args
            return fragment
        }
    }

    private var signInAccount = ""

    private var signUpPassWord = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
    }

    override fun layoutId(): Int {
        return R.layout.login_account_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.setBackgroundColor(Color.TRANSPARENT)
        viewBinder.onViewClick = this
        viewBinder.onTextListener = this
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.forget_password -> {

            }
            R.id.sign_in_tv -> {
                signIn()
            }
            R.id.sign_up_now -> {
                intoSignUp()
//                start(SignUpFragment.newInstance())
            }
        }
    }

    private fun signIn() {
        if (!checkInfo()) return

        if (!CLICK_BLE) return

        CLICK_BLE = false

        signInAccount = viewBinder.signInAccount.text.toString()
        signUpPassWord = viewBinder.signUpPassWord.text.toString()
        val maps = mapOf(
            "account" to signInAccount,
            "password" to signUpPassWord
        )

        RestClient.builder()
            .url(R.string.appLogin)
            .raw(JSON.toJSONString(maps))
            .success {
                CLICK_BLE = true
                parserAppLoginData(it)
            }
            .error { _, msg ->
                CLICK_BLE = true
                val msg0 =
                    if (msg.isNullOrEmpty()) _mActivity.getString(R.string.sign_in_failed) else msg
                onAppLoginFailed(msg0)
            }
            .failure {
                CLICK_BLE = true
                onAppLoginFailed(_mActivity.getString(R.string.sign_in_failed))
            }

            .build()
            .post()

    }

    private fun onAppLoginFailed(msg0: String) {
        Toast.makeText(_mActivity, msg0, Toast.LENGTH_SHORT).show()
    }

    private fun parserAppLoginData(it: String?) {
        Log.d("parserAppLoginData", "parserAppLoginData: $it")
        val obj = JSON.parseObject(it)
//        val expires_time = obj["expires_time"].toString()
        val token = obj["token"].toString()
        LogInTokenManager.tokenManager.saveLogInToken(token)

        onLogin()
    }

    private fun checkInfo(): Boolean {
        var flags = true

        val eTvs = arrayOf(
            viewBinder.signInAccount,
            viewBinder.signUpPassWord
        )

        for (e in eTvs) {

            val validator = e.validator()

            if (validator?.isNotEmpty() == true) {
                normalShortToast(_mActivity, validator)

                flags = false
                break
            }
        }

        return flags
    }

    override fun afterTextChanged(s: Editable?, viewId: Int) {
        when (viewId) {
            R.id.sign_in_account -> {
                signInAccount = s?.toString() ?: ""
            }
            R.id.sign_up_passWord -> {
                signUpPassWord = s?.toString() ?: ""
            }
        }
    }
}